import 'dart:async';

import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:geomancy/api/weather.dart';
import 'package:geomancy/models/current_city_model.dart';
import 'package:geomancy/models/current_weather_24h_model.dart';
import 'package:geomancy/models/current_weather_7d_model.dart';
import 'package:geomancy/models/current_weather_model.dart';
import 'package:geomancy/styles/index.dart';
import 'package:geomancy/tools/constant.dart';
import 'package:geomancy/tools/utils.dart';
import 'package:geomancy/widgets/common_text.dart';
import 'package:geomancy/widgets/common_title.dart';

class CalendarWeatherPage extends StatefulWidget {
  const CalendarWeatherPage({super.key});

  @override
  State<CalendarWeatherPage> createState() => _CalendarWeatherPageState();
}

class _CalendarWeatherPageState extends State<CalendarWeatherPage> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  CurrentCityWeatherModel? weather;    // 当前城市实时天气数据
  List<Hourly> hourlyWeather = [];    // 24小时天气预报数据（过滤后只显示12小时）
  List<Daily> daysWeather = [];       // 7天天气预报数据
  double maxTemp = 0;                 // 24小时内最高温度（用于柱状图Y轴）
  double minTemp = 0;                 // 24小时内最低温度（用于柱状图Y轴）
  Timer? _timer;                      // 定时器（用于更新当前时间）
  String currentTime = '';            // 当前时间字符串
  double totalMaxTemp = 0;            // 7天内最高温度（用于温度条计算）
  double totalMinTemp = 0;            // 7天内最低温度（用于温度条计算）
  AdInfo? adInfo;

  @override
  void initState() {
    super.initState();
    getCurrentCity();

    // 初始化时间并启动定时器
    currentTime = getCurrentDateTime();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        currentTime = getCurrentDateTime();
      });
    });
  }

  @override
  void dispose() {
    // 清理定时器
    _timer?.cancel();
    super.dispose();
  }

  ///通过ip获取地区
  Future getCurrentCity() async {
    final result = await WeatherAPI.getCurrentCity(context);
    if (result != null && result.city != null) {
      getCityLocationID(result.city!);
    }
    setState(() {
      adInfo = result;
    });
  }

  ///通过城市名称获取locationID
  Future getCityLocationID(String name) async {
    try {
      final result = await WeatherAPI.getCityLocationID(context, name);
      if (result != null && result.id != null) {
        getCurrentWeather(result.id!);
        get24HWeather(result.id!);
        get7DaysWeather(result.id!);
      }
    } catch(e) {
      //...
    }
  }

  ///实时天气
  Future getCurrentWeather(String locationId) async {
    final result = await WeatherAPI.getCurrentCityWeather(context, locationId);
    setState(() {
      weather = result;
    });
  }
  ///24小时预报（过滤奇数，只展示12小时的数据）
  Future get24HWeather(String locationId) async {
    final list = await WeatherAPI.getCurrentCityWeather24H(context, locationId);
    if (list != null && list.isNotEmpty) {
      final result = list.asMap().entries
          .where((entry) => entry.key % 2 == 0)
          .map((entry) => entry.value)
          .toList();
      List<double> temperatures = result
          .map((item) => double.parse(item.temp ?? '0'))
          .toList();
      setState(() {
        hourlyWeather = result;
        maxTemp = temperatures.reduce((curr, next) => curr > next ? curr : next);
        minTemp = temperatures.reduce((curr, next) => curr < next ? curr : next) - 10;
      });
    }
  }
  ///7天预报
  Future get7DaysWeather(String locationId) async {
    final result = await WeatherAPI.get7daysWeather(context, locationId);
    if (result != null && result.isNotEmpty) {
      // 初始化最高温和最低温为第一天的数据
      double maxTemp = double.parse(result[0].tempMax ?? '0');
      double minTemp = double.parse(result[0].tempMin ?? '0');

      for (var day in result) {
        // 获取当天的最高温和最低温
        double tempMax = double.parse(day.tempMax ?? '0');
        double tempMin = double.parse(day.tempMin ?? '0');

        // 更新7天内的最高温
        if (tempMax > maxTemp) {
          maxTemp = tempMax;
        }
        // 更新7天内的最低温
        if (tempMin < minTemp) {
          minTemp = tempMin;
        }
      }

      setState(() {
        daysWeather = result;         // 更新天气数据列表
        totalMaxTemp = maxTemp;       // 更新7天内最高温度
        totalMinTemp = minTemp;       // 更新7天内最低温度
      });
    }
  }

  /// 获取当前时间
  String getCurrentDateTime() {
    final now = DateTime.now();
    return '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')} ${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}';
  }

  List<BarChartGroupData> _generateBarGroups() {
    return List.generate(hourlyWeather.length, (index) {
      return BarChartGroupData(
        x: index,
        barRods: [
          BarChartRodData(
            fromY: minTemp,
            toY: double.parse(hourlyWeather[index].temp??'0'),
            color: const Color.fromRGBO(81, 103, 192, 1),
            width: 10.w,
            borderRadius: BorderRadius.circular(4),
          ),
        ],
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ListView(
      padding: EdgeInsets.fromLTRB(Constant.PAGEPADDING.w, 20.w, Constant.PAGEPADDING.w, 40.w),
      children: [
        // Center(child: Container(
        //   width: 510.w,
        //   height: 80.w,
        //   padding: EdgeInsets.only(left: 35.w, right: 20.w),
        //   decoration: BoxDecoration(
        //     color: ColorStyle.themeLightColor,
        //     border: Border.all(width: 5.w, color: ColorStyle.borderColor),
        //     borderRadius: BorderRadius.all(Radius.circular(40.w))
        //   ),
        //   child: Row(
        //     mainAxisAlignment: MainAxisAlignment.spaceBetween,
        //     children: [
        //       Text('搜索城市', style: TextStyle(fontSize: 30.sp, color: const Color.fromRGBO(219, 207, 174, 1)),),
        //       Image.asset('assets/icons/icon_weather_search.png', width: 30.w)
        //     ],
        //   ),
        // )),
        ///当前城市实时天气预报
        Container(
          height: 770.w,
          // margin: EdgeInsets.only(top: 20.w, bottom: 80.w),
          margin: EdgeInsets.only(bottom: 80.w),
          padding: EdgeInsets.fromLTRB(40.w, 50.w, 40.w, 44.w),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(60.w)),
            gradient: const LinearGradient(
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              colors: [
                Color.fromRGBO(31, 40, 80, 1),
                Color.fromRGBO(47, 64, 121, 1)
              ]
            ),
          ),
          child: Column(
            children: [
              //地区、时间
              Row(
                children: [
                  Text(adInfo?.district??'-', style: TextStyle(fontSize: 30.sp, color: Colors.white)),
                  SizedBox(width: 15.w),
                  Expanded(child: Text('${adInfo?.province??'-'}/${adInfo?.nation??'-'}', style: TextStyle(fontSize: 24.sp, color: Colors.white))),
                  Text(currentTime, style: TextStyle(fontSize: 24.sp, color: Colors.white)),
                ],
              ),
              //温度、图标
              Expanded(child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  if (weather?.icon != null)
                    SvgPicture.asset(
                      'assets/weather_icons/${weather!.icon}-fill.svg',
                      colorFilter: ColorFilter.mode(
                        ColorStyle.themeColor, // 设置颜色
                        BlendMode.srcIn, // 设置混合模式，通常使用 srcIn 替换原有颜色
                      ),
                      height: 130.w, // 设置高度
                      fit: BoxFit.contain, // 设置图片适配方式
                    ),
                  SizedBox(width: 30.w),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(weather?.temp != null ? '${weather?.temp}°' : '', style: TextStyle(fontSize: 80.sp, color: Colors.white)),
                      Text(weather?.text ?? '', style: TextStyle(fontSize: 30.sp, color: Colors.white)),
                    ],
                  )
                ],
              )),
              Container(
                height: 120.w,
                margin: EdgeInsets.only(top: 40.w),
                padding: EdgeInsets.symmetric(horizontal: 40.w),
                decoration: BoxDecoration(
                  color: const Color.fromRGBO(216, 216, 216, 0.1),
                  borderRadius: BorderRadius.all(Radius.circular(60.w))
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text('${weather?.windScale??'-'}级', style: TextStyle(fontSize: 24.sp, color: Colors.white)),
                        Text(weather?.windDir??'-', style: TextStyle(fontSize: 24.sp, color: Colors.white)),
                      ],
                    ),
                    // Column(
                    //   mainAxisAlignment: MainAxisAlignment.center,
                    //   children: [
                    //     Text('弱', style: TextStyle(fontSize: 24.sp, color: Colors.white)),
                    //     Text('紫外线', style: TextStyle(fontSize: 24.sp, color: Colors.white)),
                    //   ],
                    // ),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text('${weather?.vis??'-'}km', style: TextStyle(fontSize: 24.sp, color: Colors.white)),
                        Text('能见度', style: TextStyle(fontSize: 24.sp, color: Colors.white)),
                      ],
                    ),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text('${weather?.precip??'-'}mm', style: TextStyle(fontSize: 24.sp, color: Colors.white)),
                        Text('降水量', style: TextStyle(fontSize: 24.sp, color: Colors.white)),
                      ],
                    )
                  ],
                ),
              ),
              Container(
                height: 120.w,
                margin: EdgeInsets.only(top: 10.w),
                padding: EdgeInsets.symmetric(horizontal: 40.w),
                decoration: BoxDecoration(
                    color: const Color.fromRGBO(216, 216, 216, 0.1),
                    borderRadius: BorderRadius.all(Radius.circular(60.w))
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text('${weather?.humidity??'-'}%', style: TextStyle(fontSize: 24.sp, color: Colors.white)),
                        Text('相对湿度', style: TextStyle(fontSize: 24.sp, color: Colors.white)),
                      ],
                    ),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(weather?.feelsLike != null ? '${weather?.feelsLike}°' : '-', style: TextStyle(fontSize: 24.sp, color: Colors.white)),
                        Text('体感温度', style: TextStyle(fontSize: 24.sp, color: Colors.white)),
                      ],
                    ),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text('${weather?.pressure??'-'}hpa', style: TextStyle(fontSize: 24.sp, color: Colors.white)),
                        Text('大气压', style: TextStyle(fontSize: 24.sp, color: Colors.white)),
                      ],
                    )
                  ],
                ),
              )
            ],
          ),
        ),
        const CommonTitleWidget(txt: '24小时预报'),
        Container(
          height: 400.w,
          margin: EdgeInsets.only(top: 20.w, bottom: 80.w),
          padding: EdgeInsets.fromLTRB(20.w, 50.w, 20.w, 20.w),
          decoration: BoxDecoration(
            color: ColorStyle.themeLightColor,
            border: Border.all(width: 5.w, color: ColorStyle.borderColor),
            borderRadius: BorderRadius.all(Radius.circular(60.w)),
          ),
          child: BarChart(
            BarChartData(
              maxY: maxTemp,  // 最大温度值，用于定义 Y 轴范围
              minY: minTemp,  // 最小温度值
              barGroups: _generateBarGroups(),
              gridData: const FlGridData(show: false),
              borderData: FlBorderData(show: false),
              titlesData: FlTitlesData(
                bottomTitles: AxisTitles(
                  sideTitles: SideTitles(
                    showTitles: true,
                    reservedSize: 100.w,
                    getTitlesWidget: (value, meta) {
                      final index = value.toInt();
                      return Container(
                        margin: EdgeInsets.only(top: 10.w),
                        child: Column(
                          children: [
                            SvgPicture.asset(
                              'assets/weather_icons/${hourlyWeather[index].icon}-fill.svg',
                              colorFilter: ColorFilter.mode(
                                ColorStyle.themeColor, // 设置颜色
                                BlendMode.srcIn, // 设置混合模式，通常使用 srcIn 替换原有颜色
                              ),
                              width: 34.w, // 设置高度
                              fit: BoxFit.fitWidth, // 设置图片适配方式
                            ),
                            SizedBox(height: 10.w),
                            CommonText(txt: Utils.getHourByDate(hourlyWeather[index].fxTime??''), fontSize: 14.sp)
                          ],
                        ),
                      );
                    },
                    interval: 1,  // 每个小时显示一个标签
                  ),
                ),
                leftTitles: const AxisTitles(
                  sideTitles: SideTitles(showTitles: false),
                ),
                rightTitles: const AxisTitles(
                  sideTitles: SideTitles(showTitles: false),
                ),
                topTitles: AxisTitles(
                  sideTitles: SideTitles(
                    showTitles: true,
                    getTitlesWidget: (value, meta) {
                      final index = value.toInt();
                      return CommonText(txt: '${hourlyWeather[index].temp}°', fontSize: 24.sp);
                    },
                    interval: 1,  // 每个小时显示一个标签
                  ),
                ),
              ),
            ),
          ),
        ),
        const CommonTitleWidget(txt: '未来预报'),
        Container(
          height: 770.w,
          margin: EdgeInsets.only(top: 20.w, bottom: 80.w),
          padding: EdgeInsets.fromLTRB(50.w, 30.w, 0, 30.w),
          decoration: BoxDecoration(
            color: ColorStyle.themeLightColor,
            border: Border.all(width: 5.w, color: ColorStyle.borderColor),
            borderRadius: BorderRadius.all(Radius.circular(60.w)),
          ),
          child: Column(
            children: daysWeather.map((item) {
              return SizedBox(
                height: 100.w,
                child: Row(
                  children: [
                    SizedBox(
                      width: 150.w,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          CommonText(txt: Utils.getWeekDay(item.fxDate??'')),
                          Text('${item.fxDate}', style: TextStyle(fontSize: 20.sp, color: const Color.fromRGBO(124, 124, 124, 1)))
                        ],
                      ),
                    ),
                    SvgPicture.asset(
                      'assets/weather_icons/${item.iconDay}-fill.svg',
                      colorFilter: ColorFilter.mode(
                        ColorStyle.themeColor, // 设置颜色
                        BlendMode.srcIn, // 设置混合模式，通常使用 srcIn 替换原有颜色
                      ),
                      height: 50.w, // 设置高度
                      fit: BoxFit.contain, // 设置图片适配方式
                    ),
                    Container(
                      width: 70.w,
                      alignment: Alignment.centerRight,
                      child: CommonText(txt: '${item.tempMax}°')
                    ),
                    ///温度条
                    Container(
                      width: 220.w,
                      height: 10.w,
                      margin: EdgeInsets.symmetric(horizontal: 10.w),
                      child: Stack(
                        alignment: Alignment.center,
                        children: [
                          // 温度条
                          Positioned(
                            left: 220.w * (totalMaxTemp - double.parse(item.tempMax ?? '0')) / (totalMaxTemp - totalMinTemp),
                            child: Container(
                              width: 220.w * (double.parse(item.tempMax ?? '0') - double.parse(item.tempMin ?? '0')) / (totalMaxTemp - totalMinTemp),
                              height: 10.w,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.all(Radius.circular(5.w)),
                                gradient: const LinearGradient(
                                    begin: Alignment.centerLeft,
                                    end: Alignment.centerRight,
                                    colors: [
                                      Color.fromRGBO(226, 137, 105, 1),
                                      Color.fromRGBO(83, 122, 244, 1)
                                    ]
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Expanded(child: Align(
                        alignment: Alignment.centerLeft,
                        child: CommonText(txt: '${item.tempMin}°')
                    )),
                  ],
                ),
              );
            }).toList(),
          ),
        ),
      ],
    );
  }
}
